import React, {Component} from 'react'
import {View, Text, SectionList, ActivityIndicator, StyleSheet, Image, TouchableOpacity, BackHandler, Modal} from 'react-native'
import Icon from 'react-native-vector-icons/Ionicons'
import {connect} from 'react-redux'
import Enumeration, {STUDENT, TEACHER} from '../../config/enumeration'
import Badge from '../common/badge'
import {fetch_homeworks, refresh_homeworks} from '../../redux/actions/homework'
import QuickFilter from '../common/quick_filter'
import DateTimePickerTester from '../common/date_picker'
import styles from '../../config/styles'
import FormatDate from '../../helpers/timeFormat'
import DateTimePicker from 'react-native-modal-datetime-picker'
import AddNew from '../common/add_new'

class HomeworkIndex extends Component {
    static navigationOptions = ({ navigation }) => {
        const params = navigation.state.params
        if (params != undefined) {
            const _headerRight = (
                <TouchableOpacity style={styles.header_left_time_picker} onPress={params.showDatePicker}>
                    <Text style={styles.header_font}>
                        选择时间
                    </Text>
                </TouchableOpacity>
            )
           
            return {
                title: '作业',
                //headerRight: _headerRight,
                headerLeft: _headerRight
            }
        }
    }

    constructor(props) {
        super(props);
        const homework = props.homework
        this.state = {
            section_homeworks: [],
            initializing: true, //是否正在初始化，防止列表刚进来的时候就翻页
            loading: homework.loading,//列表状态，默认是加载中
            end_of_page: homework.end_of_page,//是否已经到底了
            locked: false, //点击一条作业的时候锁定列表，防止点击两下的时候触发两次
            current_page: homework.current_page,
            filter: null,
            created_at: null,
            pickingTime: false,
        };
    }

    //监控props的变化
    componentWillReceiveProps (nextProps) {
        if (nextProps.homework != undefined ) {
            const homework = nextProps.homework
            this.state.loading = false
            this.state.initializing = false
            this.state.current_page = homework.current_page
            this.state.end_of_page = homework.end_of_page
            this.transform_homeworks_for_section(homework.homeworks)        
            this.setState()
        }
      
        //alert(this.state.receivedCount)
    }

    //对数据进行转换
    transform_homeworks_for_section = (homeworks) => {
        let _transformation_data = {}
        this.state.section_homeworks = []
        /* 
          先对取到的数据进行转换，转换成按照时间分组的形式
          Exsample
          {
              "2017-11-21": [...],
              "2017-11-20": [...]
          }
          然后再用_transformation_data对state.homeworks进行筛选，如果没有就新建一个section
          最终再变成<SectionList />所需要的形式
          Exsample
            [
                {data: [...], title: ...},
                {data: [...], title: ...},
                {data: [...], title: ...},
            ]
        */
        homeworks.forEach((homework) => {
            if (_transformation_data[homework.created_date] == undefined) {
                _transformation_data[homework.created_date] = []
            }
            _transformation_data[homework.created_date].push(homework)
        })

        Object.keys(_transformation_data).forEach((key) => {
            let old_section_obj = this.state.section_homeworks.filter((section_obj) => {
                return section_obj.title == key
            })
            if (old_section_obj.length == 0) {
                new_section_object = {
                    title: key,
                    data: _transformation_data[key]
                }
                this.state.section_homeworks.push(new_section_object)
            } else {
                old_section_obj[0].data.push(..._transformation_data[key])
            }
        })
    }

    //获取作业
    fetch_homeworks = () => {
        const {filter, created_at} = this.state
        this.props.dispatch(fetch_homeworks(filter, created_at || ""))
    }

    componentWillMount() {
        this.fetch_homeworks()
        let backPressClickTimeStamp = 0
        BackHandler.addEventListener('hardwareBackPress', () => {
            let timestamp = new Date()
            if (timestamp - backPressClickTimeStamp > 2000) {
              backPressClickTimeStamp = timestamp
              Toast.show('再按一次退出程序')
              return true
            } else {
              return false
            }
        })
    }

    componentDidMount() {
        setTimeout(() => {this.setState({initializing: false})}, 1000)
        if (this.props.user.user.role == TEACHER) {
            this.props.navigation.setParams({isTeacher: true})         
        }
        //设定头部组件里面的时间选择
        this.props.navigation.setParams({
           showDatePicker: () => {
               this.setState({pickingTime: true})
           }
        })

    }

    //用于sectionlist的key
    _keyExtractor = (item, index) => index

    //根据角色返回不一样的状态显示
    _status_bar_with_role = (role, item) => {
        //2是学生， 1和3是老师
        if (role == STUDENT) {
            const status = Enumeration.Homework.Status(item.status)
            const color = this._get_color_from(status)
            const icon_area = this._get_icon_area(status)
            return(
                <View>
                    <View style={{flex: 1, flexDirection: 'row', justifyContent: 'center'}}>
                        <View style={{justifyContent: 'center'}}>
                            {icon_area}
                        </View>
                        <View style={{justifyContent: 'center'}}>
                            <Text style={[styles.status_label_text, {color: color}]}>{status}</Text>
                        </View>
                    </View>
                </View>
               
            )
        } else {
            const weijiao_count = item.assignno - item.answerno - item.replyno

            return(
                <View>

                    {item.status == 'init' ?<View style={[styles.light_radius_btn]}><Text style={{ fontSize:12,color:'#b2b4b3'}}>未交</Text></View>:item.status == 'pending' ?<View style={[styles.blue_radius_btn]}><Text style={{fontSize:12,color:'#fff'}}>待批</Text></View>:<View style={[styles.light_radius_btn]}><Text style={{fontSize:12,color:'#b2b4b3'}}>完成</Text></View>}
                </View>
            )

            //return(
            //    <View>
            //        <View style={{flex: 1, justifyContent: 'center'}}>
            //            {item.answerno > 0 ? (<View>
            //                                    <Text style={[styles.status_label_text, {color: '#ff4e17'}]}>待批: {item.answerno}</Text>
            //                                </View>) : null
            //            }
            //        <View>
            //            <Text style={[styles.status_label_text, {color: '#ff951a'}]}>未交: {weijiao_count}</Text>
            //        </View>
            //        <View>
            //            <Text style={[styles.status_label_text, {color: '#707070'}]}>完成: {item.replyno}</Text>
            //            </View>
            //        </View>
            //    </View>
            //)
        }
    }
    
    //每一条item的渲染模板
    _renderItem = (section) => {
        const role = this.props.user.user.role //2是学生， 1和3是老师
        const item = section.item
        const task_count = item.include_tasks ? item.task_count : 1
        //这里需要根据角色来跳转不同的页面    
        return(
            <TouchableOpacity
                style={styles.list_item_container}
                onPress={() => {this._link_to_show(item)}}
            >
                <View style={{flex: 1, flexDirection: 'row'}}>
                    <View style={{flex: 1}}>
                        <View style={{flexDirection: 'row'}}>
                            {/*item.if_has_attachments ? <Icon name={'ios-attach'} size={20} /> : null*/}
                            <Text 
                                style={styles.list_item_text} 
                                numberOfLines={1}
                            >
                                {item.title}
                            </Text>
                        </View>
                        <Text style={[styles.text_label_grey]}>
                            {`${task_count}个作业`}
                            {/* {item.answerno}<Text style={[styles.text_label_grey]}>/{item.answerno+item.assignno}</Text> */}
                        </Text>

                    </View>
                    {this._status_bar_with_role(role, item)}
                </View>
        </TouchableOpacity>
        )
    };

    //头部组件
    _headerComponent = () => {
        var role = this.props.user.user.role //2是学生， 1和3是老师
        var check_text = role == STUDENT ? "待订":"待批";
        return (
            <View style={{flexDirection: 'row', height: 40, backgroundColor: 'white'}}>
                <QuickFilter
                    onPress={() => {this._filter_homeworks('all')}}
                    active={["all", null].includes(this.state.filter)}
                    activeIconName={'ios-crop'}
                    unactiveIconName={'ios-crop-outline'}
                    filterName={'全部'}
                />
                <QuickFilter
                    onPress={() => {this._filter_homeworks('undo')}}
                    active={this.state.filter == 'undo'}
                    activeIconName={'ios-undo'}
                    unactiveIconName={'ios-undo-outline'}
                    filterName={'未完成'}
                />
                <QuickFilter
                    onPress={() => {this._filter_homeworks('tocheck')}}
                    active={this.state.filter == 'tocheck'}
                    activeIconName={'ios-create'}
                    unactiveIconName={'ios-create-outline'}
                    filterName={check_text}
                />
                <DateTimePicker
                    isVisible={this.state.pickingTime}
                    onConfirm={(date) => this.filterTime(FormatDate(date))}
                    onCancel={() => this.setState({pickingTime: false})}
                    date={this.state.created_at ? new Date(this.state.created_at) : new Date()}
                    cancelTextIOS={'取消'}
                    confirmTextIOS={'确定'}
                    titleIOS={'选择日期'}
                />
            </View>
        )
    };

    //尾部组件
    _footerComponent = () => {
        let text
        if (this.state.end_of_page) {
            text = '已经没有数据了'
        } else {
            text = '正在加载数据...'
        }
        return (
            <View style={{alignItems: 'center', backgroundColor: '#f6f6f6'}}>
                <Text>{text}</Text>
            </View>
        )
    };

    //分组后的header
    _sectionHeader = (item) => {
        return(
            <View style={styles.section_header_container}>
                <Text style={styles.section_header_text}>
                    {item.section.title}
                </Text>
            </View>
        ) 
    };

    _link_to_show = (item) => {
        if (this.state.locked) {
            return false
        } else {
            const {role} = this.props.user.user //2是学生， 1和3是老师
            let target_component
            if (item.include_tasks) {
                //新版本的带课文的数据
                target_component = 'homework_task_list'
            } else {
                //这里需要根据角色来跳转不同的页面
                target_component = role == STUDENT ? 'homeworks_show' : 'homeworks_correcting'
            }
           
            this.props.navigation.navigate(target_component, {
                id: item.id,
                refresh: () => {
                    this._refresh()
                }
            })
            this.state.locked = true
            setTimeout(() => {this.state.locked = false}, 200)
        }
    };

    //获取状态颜色
    _get_color_from = (status) => {
        switch (status) {
            case "未完成":
                return "#ff951a";
            case /完成|已订/:
                return "#707070";
            case "待订":
                return "#ff4e17";
            default:
                return "#707070"
        }
    };

    //获取状态icon name
    _get_icon_area = (status) => {
        switch (status) {
            case "未完成":
                return (<Icon name={"ios-undo-outline"} size={30} color="#ff951a" />);
            case /完成|已订/:
                return (<Icon name={"ios-checkmark-outline"} size={40} color="#707070" />);
            case "待订":
                return (<Icon name={"ios-create-outline"} size={30} color="#ff4e17"/>);
            default:
                return (<Icon name={"ios-send-outline"} size={30}  color="#707070"/>);
        }
    };


    //刷新列表
    _refresh = () => {
        this.props.dispatch(refresh_homeworks(this.state.filter)) 
    }

    //翻页
    _flip = () => {
        if (this.state.initializing || this.state.loading)
            return
        else if (this.state.end_of_page) {
            Toast.show('没有更多数据了')
        } else {
            this.fetch_homeworks()
        }
    }

     //筛选状态
     _filter_homeworks = (filter) => {
        if (this.state.initializing || this.state.loading)
            return false
        else {
            this.setState({filter: filter, initializing: true, created_at: null}, () => {
                this.props.dispatch(refresh_homeworks(filter, ""))
            })
        }    
    }

    //筛选时间
    filterTime = (time) => {
        if (this.state.initializing || this.state.loading)
            return
        else {
            this.setState({
                created_at: FormatDate(time),
                pickingTime: false, 
                initializing: true,
                filter: null
            }, () => {
                this.props.dispatch(refresh_homeworks(null, time))
            })
        } 
    }

    render () {
        const {user, navigation} = this.props
        return (
            <View style={styles.main_body}>
                {this._headerComponent()}
                <SectionList
                    keyExtractor={this._keyExtractor}
                    renderSectionHeader={this._sectionHeader}
                    //ListHeaderComponent={this._headerComponent}
                    ListFooterComponent={this._footerComponent}                    
                    renderItem={this._renderItem}
                    extraData={this.props}
                    sections={this.state.section_homeworks}
                    onRefresh={this._refresh}
                    refreshing={this.state.loading}
                    onEndReachedThreshold={0.1}
                    onEndReached={this._flip.bind(this)}
                    stickySectionHeadersEnabled={true}
                    ItemSeparatorComponent={() => {return (<View style={{height: 5}} />)}}     
                    SectionSeparatorComponent={() => {return (<View style={{height: 5}} />)}}   
                    style={{flex: 1}}  
                />
                {user.user.role == TEACHER ? (
                    <AddNew 
                        onPress={() => {navigation.navigate('new_homework_with_text', {
                            refresh: () => this._refresh()
                        })}} 
                        onLongPress={() => navigation.navigate('new_homework_without_text', {
                            refresh: () => this._refresh()
                        })}
                    />) 
                    : 
                    null
                }
            </View>
        )  
    }
}

// const styles = StyleSheet.create({
   
//   });

const mapStateToProps = (state) => {
    return {
        user: state.user,
        homework: state.homework
    }
}

export default connect(mapStateToProps)(HomeworkIndex)